package com.micro.controller;

import com.micro.dto.TrainOrderDTO;
import com.micro.entity.TrainTicketOrder;
import com.micro.request.TicketCreatingRequest;
import com.micro.service.TrainTicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/train-orders")
public class TrainTicketOrderController {

    @Autowired
    private TrainTicketOrderService trainTicketOrderService;

    // 创建火车票订单
    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody List<TicketCreatingRequest> orderRequests) {
        try {
            for (TicketCreatingRequest request : orderRequests) {
                // 验证必要参数
                if (request.getDate() == null || request.getTrainNumber() == null
                        || request.getSeatType() == null || request.getUserName() == null) {
                    return ResponseEntity.badRequest().body("缺少必要参数");
                }
                // 调用Service创建订单
                trainTicketOrderService.createOrder(request);
            }
            return ResponseEntity.ok().body("订单创建成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("订单创建失败: " + e.getMessage());
        }
    }

    // 根据用户名查询订单
    @GetMapping("/user/{username}")
    public ResponseEntity<List<TrainTicketOrder>> getOrdersByUsername(@PathVariable String username) {
        try {
            List<TrainTicketOrder> orders = trainTicketOrderService.getOrdersByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据用户名查询历史订单（DTO格式）
    @GetMapping("/user/{username}/history")
    public ResponseEntity<List<TrainOrderDTO>> getOrderHistoryByUsername(@PathVariable String username) {
        try {
            List<TrainOrderDTO> orders = trainTicketOrderService.getOrderDTOsByUsername(username);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据订单ID查询订单详情
    @GetMapping("/{orderId}")
    public ResponseEntity<TrainTicketOrder> getOrderById(@PathVariable Long orderId) {
        try {
            TrainTicketOrder order = trainTicketOrderService.getOrderById(orderId);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 退票
    @PostMapping("/{orderId}/refund")
    public ResponseEntity<String> refundOrder(@PathVariable Long orderId) {
        try {
            boolean success = trainTicketOrderService.refundOrder(orderId);
            if (success) {
                return ResponseEntity.ok("退票成功");
            } else {
                return ResponseEntity.badRequest().body("退票失败：订单不存在或状态不允许退票");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("退票失败: " + e.getMessage());
        }
    }

    // 根据用户ID查询订单
    @GetMapping("/user-id/{userId}")
    public ResponseEntity<List<TrainTicketOrder>> getOrdersByUserId(@PathVariable Long userId) {
        try {
            List<TrainTicketOrder> orders = trainTicketOrderService.getOrdersByUserId(userId);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据车票状态查询订单
    @GetMapping("/status/{ticketStatus}")
    public ResponseEntity<List<TrainTicketOrder>> getOrdersByTicketStatus(@PathVariable Byte ticketStatus) {
        try {
            List<TrainTicketOrder> orders = trainTicketOrderService.getOrdersByTicketStatus(ticketStatus);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 根据列车ID查询订单
    @GetMapping("/train/{trainId}")
    public ResponseEntity<List<TrainTicketOrder>> getOrdersByTrainId(@PathVariable Long trainId) {
        try {
            List<TrainTicketOrder> orders = trainTicketOrderService.getOrdersByTrainId(trainId);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }
}
